package com.whjh.image.conpression.task;

import java.io.File;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;

public class ImageCompressionTask {

	@Value("${image.conpression.path}")
	private String basePath;

	@Value("${image.conpression.checkDayNum}")
	private Integer checkDayNum;

	@Value("${image.conpression.limitSize:1498}")
	private Integer limitSize;

	protected void doExecute() {
		int count = -checkDayNum;
		while (count <= 0) {
			count++;
			Date date = new Date();
			date = DateUtil.offsetDay(date, count);
			checkAndExecuteCompression(date);
		}
	}

	private void checkAndExecuteCompression(Date date) {
		String dir = basePath + DateUtil.format(date, "yyyyMMdd") + "\\";
		if (!FileUtil.exist(dir)) {
			return;
		}
		List<String> listFileNames = FileUtil.listFileNames(dir);
		for (String file : listFileNames) {
			conpression(dir + file);
		}
	}

	public void conpression(String filePath) {
		File file = new File(filePath);
		byte[] inByte = FileUtil.readBytes(file);
		long size = inByte.length;
		if (size <= limitSize) {
			return;
		}
		byte[] outByte = ThumbnailsUtils.compressPicForScaleToBytesBinarySearch(inByte, limitSize, filePath);
		FileUtil.writeBytes(outByte, file);
	}

}
